package com.example.album;

import java.util.HashMap;
import java.util.Map;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AdminService {
    @Autowired
    private CategoryRepository cr;
    @Autowired
    private UserRepository ur;
    @Autowired
    private AlbumRepository ar;

    public Map<String, Object> addCategory(String categoryName) {
        Map<String, Object> result = new HashMap<>();

        Category category = cr.findByCategoryName(categoryName);
        if (category != null) {
            result.put("success", false);
            result.put("message", "类别已存在");
            return result;
        }
        category = new Category();
        category.setCategoryName(categoryName);
        //使用uuid前16位作为类别id
        category.setCategoryId(java.util.UUID.randomUUID().toString().substring(0, 16));
        cr.save(category);
        result.put("success", true);
        return result;
    }

    public Map<String, Object> deleteCategory(String categoryName) {
        Map<String, Object> result = new HashMap<>();

        Category category = cr.findByCategoryName(categoryName);
        if (category == null) {
            result.put("success", false);
            result.put("message", "类别不存在");
            return result;
        }
        
        // 先查找该类别对象，获取其categoryId
        List<Album> albums = ar.findByCategoryId(category.getCategoryId());
        if (!albums.isEmpty()) {
            //把列表内所有相册的Category_id设为1
            for (Album album : albums) {
                album.setCategoryId("1");
                ar.save(album);
            }
        }
        cr.delete(category);
        result.put("success", true);
        return result;
    }

    public Map<String, Object> banUser(String userId) {
        Map<String, Object> result = new HashMap<>();
        User user = ur.findByUserId(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        user.setStatus(1); // 假设1表示封禁状态
        ur.save(user);
        result.put("success", true);
        return result;
    }

    public Map<String, Object> unbanUser(String userId) {
        Map<String, Object> result = new HashMap<>();
        User user = ur.findByUserId(userId);
        if (user == null) {
            result.put("success", false);
            result.put("message", "用户不存在");
            return result;
        }
        user.setStatus(0); // 假设0表示未封禁状态
        ur.save(user);
        result.put("success", true);
        return result;
    }
}
